package com.xuecheng.framework.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 校验传入的page与size
 */
@Component
public class VerifyPageableInterceptor implements HandlerInterceptor {

    // 在业务处理器处理请求之前被调用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        //被拦截请求都会在这里进行处理
        Map map = (Map) request.getAttribute("org.springframework.web.servlet.HandlerMapping.uriTemplateVariables");
        if (map != null && map.size()>0){
            Integer size = Integer.parseInt(map.get("size").toString());
            Integer page = Integer.parseInt(map.get("page").toString());
            if(page<=0){
                page = 1;
            }
            page--;
            if (size<=0 || size >=100){
                size = 10;
            }

            map.put("page",page.toString());
            map.put("size",size.toString());

        }
        return true;
    }


}
